import React from 'react';
import moment from 'moment';
import { Form, Input, Button, DatePicker, Select } from 'antd';

const RangePicker = DatePicker.RangePicker;

function range(start, end) {
  const result = [];
  for (let i = start; i < end; i++) {
    result.push(i);
  }
  return result;
}

function disabledDate(current) {
  return current && current > moment().endOf('day');
}

function disabledDateTime() {
  return {
    disabledHours: () => range(0, 24).splice(moment().hour() + 1),
  };
}

class SearchForm extends React.Component {
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      let postvalue = {};
      //console.log('Received values of form: ', values);
      for (let key of Object.keys(values)) {
        if (values[key] !== undefined && values[key] !== '') {
          postvalue[key] = values[key];
        }
      }
      if (postvalue.date && postvalue.date.length > 0) {
        const startDate = postvalue.date[0].format('YYYY-MM-DD');
        const endDate = postvalue.date[1].format('YYYY-MM-DD');
        postvalue = {
          ...postvalue,
          startDate,
          endDate,
        };
        delete postvalue.date;
      }
      this.props.onSearch(postvalue);
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form layout="inline" onSubmit={this.handleSubmit}>
        <Form.Item>
          {getFieldDecorator('date')(
            <RangePicker
              format="YYYY-MM-DD HH[:00:00]"
              disabledDate={disabledDate}
              disabledTime={disabledDateTime}
              showTime={{ format: 'HH' }}
            />
          )}
        </Form.Item>
        <Form.Item>{getFieldDecorator('iccid')(<Input placeholder="ICCID" />)}</Form.Item>
        <Form.Item>{getFieldDecorator('devId')(<Input placeholder="设备的ID" />)}</Form.Item>
        <Form.Item>
          {getFieldDecorator('online')(
            <Select style={{ width: 180 }} placeholder="在线状态">
              <Select.Option value="">无</Select.Option>
              <Select.Option value={1}>在线</Select.Option>
              <Select.Option value={0}>离线</Select.Option>
            </Select>
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('status')(
            <Select style={{ width: 180 }} placeholder="SIM卡状态">
              <Select.Option value="">无</Select.Option>
              <Select.Option value={1}>已激活</Select.Option>
              <Select.Option value={0}>已停用</Select.Option>
            </Select>
          )}
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            查询
          </Button>
        </Form.Item>
      </Form>
    );
  }
}

export default Form.create({ name: 'search_form' })(SearchForm);
